//
//  RadioPlayerController.m
//  StayAwhile
//
//  Created by dllo on 16/2/25.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "RadioPlayerController.h"
#import "TXPPlayView.h"
#import "TXPRadioModel.h"
@interface RadioPlayerController ()

@property (nonatomic,strong) TXPPlayView *music;
@end

@implementation RadioPlayerController
+(instancetype)sharePlayerViewController{
    
    static RadioPlayerController *music = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        music = [[RadioPlayerController alloc] init];
        
    });
    
    return music;
}
// 歌曲id
- (void)setTingid:(NSString *)tingid{
    
    _tingid = tingid;
    if (self.player.state == STKAudioPlayerStatePaused) {
        [self.music.playButton setImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];
       
    }
    else if (self.player.state == STKAudioPlayerStatePlaying){
        
        [self.music.playButton setImage:[UIImage imageNamed:@"iconfont-bofang-5.png"] forState:UIControlStateNormal];
        
        
    }

//    [self playMusic];
}
- (void)playMusic{
    
    
    [TXPAFNetworkingBlock PostAFNURLWithString:@"http://api2.pianke.me/ting/info" Body:@{@"auth":@"D5JqESWyo65DCsV8HMPqm1TJxQJDm2ZrSIpDtkUWNm1cWP229FNSBxa7fw", @"client":@"2", @"tingid":self.tingid} Cookie:nil  resultBlock:^(id result) {
        
        NSLog(@"--------result%@",result);
        
        NSMutableDictionary *dic = [result objectForKey:@"data"];
        TXPRadioModel *model = [TXPRadioModel modelWithDictionary:dic];
        [self.player play:model.Info.musicUrl];
        self.music.modle = model;
              self.timer = [NSTimer scheduledTimerWithTimeInterval:1.f target:self selector:@selector(track) userInfo:nil repeats:YES];
    } errorBlock:^(NSError *error) {
        
    }];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
   
    self.player = [[STKAudioPlayer alloc] initWithOptions:(STKAudioPlayerOptions){ .flushQueueOnSeek = YES, .enableVolumeMixer = YES, .equalizerBandFrequencies = {50, 100, 200, 400, 800, 1600, 2600, 16000} }];
    self.player.volume = 0.5;
    self.player.meteringEnabled = YES;// 是否启用音频测量,默认为no,一旦启用音频测量可以通过updateMeters方法更新测量值
    
   [[NSUserDefaults standardUserDefaults] setObject:@"顺序播放" forKey:@"playMode"];
    self.music = [[TXPPlayView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)];
    [self.view addSubview:self.music];
    [self createSubplayerView];

  
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(20, 30, 20, 20);
    [button setImage:[UIImage imageNamed:@"iconfont-fanhui-3.png"] forState:UIControlStateNormal];
    [button addTarget:self action:@selector(leftAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = CGRectMake(WIDTH - 50, 30, 20, 20);
    [button1 setImage:[UIImage imageNamed:@"iconfont-anniu.png"] forState:UIControlStateNormal];
    [self.view addSubview:button1];
    [button1 addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
}
- (void)rightAction:(UIButton *)bnt{
    
    
}

- (void)leftAction:(UIButton *)bnt{
    
   
   [self dismissViewControllerAnimated:YES completion:^{
       
       
   }];
    
}
#pragma  mark - 创建播放器 按钮
- (void)createSubplayerView{
    
    [self.music.upButton addTarget:self action:@selector(upButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.music.nextButton addTarget:self action:@selector(nextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.music.sliderMusic addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    [self.music.playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.music.slider addTarget:self action:@selector(slider:) forControlEvents:UIControlEventValueChanged];
     [self.music.playBnt addTarget:self action:@selector(playBntAction:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)playBntAction:(UIButton *)bnt{
    
   static int a = 0;
    
    if (a % 3 == 0) {
        
        [self.music.playBnt setImage:[UIImage imageNamed:@"iconfont-shunxuxunhuan.png"] forState:UIControlStateNormal];
       
    }else if (a % 3 == 1) {
        
        [self.music.playBnt setImage:[UIImage imageNamed:@"iconfont-suijibofang.png"] forState:UIControlStateNormal];
        [[NSUserDefaults standardUserDefaults] setObject:@"随机播放" forKey:@"playMode"];
    }else if (a % 3 == 2) {
        
        [self.music.playBnt setImage:[UIImage imageNamed:@"iconfont-yuledanquxunhuan-copy.png"] forState:UIControlStateNormal];
        [[NSUserDefaults standardUserDefaults] setObject:@"单曲循环" forKey:@"playMode"];
    }
    a++;
    NSLog(@"a = %d",a);
}
- (void)slider:(UISlider *)sender{
    
    self.player.volume = sender.value;
    
}

- (void)upButtonAction:(UIButton *)btn{
    
    
    if (self.indexRow != 0) {
        self.indexRow = (self.indexRow - 1);
    }
    else
    {
        btn.enabled = NO;
    }
    
    TXPRadioModel *sing = [self.allMusicArray objectAtIndex:self.indexRow];
    self.tingid = sing.tingid;
    
}

- (void)nextButtonAction:(UIButton *)sender{
    
    self.indexRow = (self.indexRow + 1) % self.allMusicArray.count;
    NSLog(@"indexRow = %ld",self.indexRow);
    // 如果歌曲总数大于当前播放音乐下标
    if (self.indexRow < self.allMusicArray.count) {
        
        TXPRadioModel *model = [self.allMusicArray objectAtIndex:self.indexRow];
        self.tingid = model.Info.tingid;
        
    }else{
        
        // 如果总数小于当前下标,直接播放取余数后的,也就是从第一个播放
        
        [self playMusic];
    }
    self.music.upButton.enabled = YES;
    
}

- (void)sliderAction:(UISlider *)slider{
    
    if (self.player) {
        
        [self.player seekToTime:slider.value];
    }
    
}
#pragma mark - 播放按钮
- (void)playButtonAction:(UIButton *)bnt{
    
    NSLog(@"%d",self.player.state);
    if (self.player.state == STKAudioPlayerStatePaused) {
        
       
          [self.music.playButton setImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];
              [self.player resume];
    }
    else if (self.player.state == STKAudioPlayerStatePlaying){
        
       [self.music.playButton setImage:[UIImage imageNamed:@"iconfont-bofang-5.png"] forState:UIControlStateNormal];
        
        [self.player pause];
    }else{
        
        [self playMusic];
        
    }
    
    [self.music stopImgeView];
    
}
- (void)track{
    
    NSLog(@"%@",self.player);
    self.music.sliderMusic.maximumValue = self.player.duration; // 音乐总时长
    self.music.sliderMusic.value = self.player.progress; // 当前进度
    NSInteger proMin = (NSInteger)self.player.progress / 60; // 当前秒
    NSInteger proSec = (NSInteger)self.player.progress % 60; // 当前分钟
    // duration 总时长
    NSInteger durMin = (NSInteger)self.player.duration / 60; // 总秒
    NSInteger durSec = (NSInteger)self.player.duration % 60; // 总分钟
    
    self.music.timeLab.text = [NSString stringWithFormat:@"%02ld:%02ld / %02ld:%02ld", proMin, proSec, durMin, durSec];
    
    if ((NSInteger)self.music.sliderMusic.value + 1 == (NSInteger)self.music.sliderMusic.maximumValue) {
        if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"playMode"] isEqualToString:@"顺序播放"])
        {
            [self nextButtonAction:nil];
        }
        else if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"playMode"] isEqualToString:@"单曲循环"])
        {
            [self playMusic];
            
        }
        else if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"playMode"] isEqualToString:@"随机播放"])
        {
            //                NSLog(@"随机播放");
            self.indexRow = arc4random()%(self.allMusicArray.count+1);
            
            TXPRadioModel *model = [self.allMusicArray objectAtIndex:self.indexRow];
           
            self.tingid = model.tingid;
            
        }
        

    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
